package com.liuyz.writer_;

import org.junit.Test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class 缓冲字符输出流 {

    // 使用处理流保存数据至文件
    @Test
    public void writer_1() {
        String path = "d:\\test.txt";
        BufferedWriter bufferedWriter = null;
        try {
            // 构建处理流对象，传入节点流对象
            // bufferedWriter = new BufferedWriter(new FileWriter(path));
            // 该处理流并没有提供可追加的模式，因此只能在节点流中设置追加模式
            bufferedWriter = new BufferedWriter(new FileWriter(path, true));

            bufferedWriter.write("测试");
            // 插入一个和系统相关的换行符
            bufferedWriter.newLine();
            bufferedWriter.write("李四");
            bufferedWriter.newLine();
            bufferedWriter.write("233");
            bufferedWriter.newLine();

            // 调用处理流的flush方法时，会自动调用节点流的flush方法
            bufferedWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != bufferedWriter) {
                try {
                    // 关闭处理流时，会自动调用节点流的close方法
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
